package com.shengqin.calculate;

import com.shengqin.calculate.data.CalculateContext;
import com.shengqin.entity.TestResult;
import com.shengqin.pojo.plan.result.ScoreResult;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractCalculateScoreComponent {
    protected void calculateTestResultScore(TestResult testResult, TestResult oldTestResult, ScoreResult scoreResult, CalculateContext context) {
        BigDecimal prjWeight = context.getHealthProject().getPrjWeight();
        String projectType = context.getHealthProject().getPrjType();

        if (scoreResult != null) {
            if (scoreResult.getScore() != null) {
                testResult.setScore(new BigDecimal(scoreResult.getScore().toString()));
                testResult.setStandardScore(scoreResult.getStandardScore());
                testResult.setExtraScore(scoreResult.getExtraScore());
                testResult.setLevel(scoreResult.getLevel());
                if (prjWeight != null) {
                    if (scoreResult.getExtraScore().compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal finalScore = scoreResult.getScore().subtract(scoreResult.getExtraScore()).setScale(4, RoundingMode.HALF_UP);
                        testResult.setFinalScore(finalScore.multiply(prjWeight).add(scoreResult.getExtraScore()));
                    } else {
                        testResult.setFinalScore(scoreResult.getScore().multiply(prjWeight).setScale(4, RoundingMode.HALF_UP).add(scoreResult.getExtraScore()));
                    }
                }
            } else {
                testResult.setScore(BigDecimal.ZERO);
                testResult.setStandardScore(BigDecimal.ZERO);
                testResult.setExtraScore(BigDecimal.ZERO);
                testResult.setFinalScore(BigDecimal.ZERO);
                testResult.setLevel("不及格");
            }

            if (ObjectUtils.isEmpty(oldTestResult)) {
                context.getCalculateResultList().add(testResult);
                if (!CollectionUtils.isEmpty(context.getHeightWeightTestResultList())) {
                    context.getCalculateResultList().addAll(context.getHeightWeightTestResultList());
                }
            } else {
                boolean isAdd = false;
                boolean isAddHeightWeight = false;
                boolean isDeleteOldResult = false;

                if (!StringUtils.hasLength(testResult.getDeviceNo()) || (StringUtils.hasLength(context.getUploadType()) && context.getUploadType().equals("arbitrate"))) {
                    isAdd = true;
                    if ("BMI".equalsIgnoreCase(testResult.getPrjName())) {
                        if (!CollectionUtils.isEmpty(context.getHeightWeightTestResultList())) {
                            isAddHeightWeight = true;
                        }
                    }
                    if (!ObjectUtils.isEmpty(oldTestResult)) {
                        isDeleteOldResult = true;
                    }
                } else {
                    if ("2".equals(context.getPlan().getPlanRuleType())) {
                        if (oldTestResult.getPrjName().equals(testResult.getPrjName()) && oldTestResult.getGradeId().equals(testResult.getGradeId())) {
                            if (oldTestResult.getFinalScore() == null && testResult.getFinalScore() != null) {
                                isDeleteOldResult = true;
                                isAdd = true;
                            } else if (testResult.getFinalScore() != null) {
                                if (testResult.getFinalScore().compareTo(oldTestResult.getFinalScore()) > 0) {
                                    isDeleteOldResult = true;
                                    isAdd = true;
                                    if ("BMI".equalsIgnoreCase(testResult.getPrjName())) {
                                        if (!CollectionUtils.isEmpty(context.getHeightWeightTestResultList())) {
                                            isAddHeightWeight = true;
                                        }
                                    }
                                } else if (testResult.getFinalScore().compareTo(oldTestResult.getFinalScore()) == 0) {
                                    if (StringUtils.hasLength(projectType) && (projectType.contains("计时") || projectType.equalsIgnoreCase("计时"))) {
                                        if (StringUtils.hasLength(oldTestResult.getResult())) {
                                            try {
                                                BigDecimal oldResult = transferResult(oldTestResult.getResult(), context.getPlan().getCalculateType() == 2 ? context.getHealthProject().getRadixType() : "", context.getHealthProject().getRadixLength());
                                                if (scoreResult.getRealResult().compareTo(oldResult) <= 0) {
                                                    isDeleteOldResult = true;
                                                    isAdd = true;
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    } else {
                                        if (StringUtils.hasLength(oldTestResult.getResult())) {
                                            BigDecimal oldResult = new BigDecimal(oldTestResult.getResult());
                                            if (scoreResult.getRealResult().compareTo(oldResult) >= 0) {
                                                isDeleteOldResult = true;
                                                isAddHeightWeight = true;
                                                isAdd = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else if ("1".equals(context.getPlan().getPlanRuleType())) {
                        isAdd = true;
                        if ("BMI".equalsIgnoreCase(testResult.getPrjName())) {
                            if (!CollectionUtils.isEmpty(context.getHeightWeightTestResultList())) {
                                isAddHeightWeight = true;
                            }
                        }
                        if (!ObjectUtils.isEmpty(oldTestResult)) {
                            isDeleteOldResult = true;
                        }
                    }
                }

                if (isAdd) {
                    context.getCalculateResultList().add(testResult);
                }
                if (isAddHeightWeight) {
                    if (!CollectionUtils.isEmpty(context.getHeightWeightTestResultList())) {
                        context.getCalculateResultList().addAll(context.getHeightWeightTestResultList());
                    }
                }
                if (isDeleteOldResult) {
                    context.getDeleteOldResultIdList().add(oldTestResult.getId());
                    if ("BMI".equalsIgnoreCase(testResult.getPrjName())) {
                        List<TestResult> oldHeightWeightList = context.getAllOldTestResultList().stream().filter(t -> "身高".equals(t.getPrjName()) || "体重".equals(t.getPrjName())).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(oldHeightWeightList)) {
                            context.getDeleteOldResultIdList().addAll(oldHeightWeightList.stream().map(TestResult::getId).collect(Collectors.toList()));
                        }
                    }
                }
            }
        } else {
            context.getCalculateResultList().add(testResult);
        }
    }

    public BigDecimal transferResult(String result, String radixType, Integer radixLength) {
        if (StringUtils.hasLength(result)) {
            if (result.contains(":")) {
                result = result.replaceAll("\\.", ":");
                String[] texts = result.split(":");
                BigDecimal minutes = new BigDecimal(Integer.parseInt(texts[0]) * 60);
                BigDecimal second = new BigDecimal(Integer.parseInt(texts[1]));
                BigDecimal millisecond = new BigDecimal(Integer.parseInt(texts[2])).divide(new BigDecimal("1000"), 3, RoundingMode.DOWN);
                if (StringUtils.hasLength(radixType)) {
                    BigDecimal millisecondDecimal = transferMillisecond(texts[2], radixType, radixLength);
                    return minutes.add(second).add(millisecondDecimal);
                }
                return minutes.add(second).add(millisecond);
            } else if ((result.contains("'") || result.contains("′"))) {
                String finalValue = result;
                finalValue = finalValue.replaceAll("'", "′");
                finalValue = finalValue.replaceAll("\"", "″");

                String[] values = finalValue.split("′");
                Integer valueMin = Integer.parseInt(values[0]) * 60;
                Integer valueSecond = Integer.valueOf(values[1].replaceAll("″", ""));
                return new BigDecimal(valueMin + valueSecond);
            } else {
                return new BigDecimal(result);
            }
        }
        return null;
    }

    private BigDecimal transferMillisecond(String millisecondText, String radixType, Integer radixLength) {
        BigDecimal millisecondDecimal = new BigDecimal(millisecondText);
        if (radixType.equalsIgnoreCase("不取舍")) {
            if (radixLength == 0) {
                return BigDecimal.ZERO;
            }
            if (millisecondText.length() >= 2) {
                String millisecondText2 = millisecondText.substring(0, 1);
                return new BigDecimal(millisecondText2 + "00").divide(new BigDecimal("1000"), radixLength, RoundingMode.HALF_UP);
            }
        } else {
            BigDecimal divide = millisecondDecimal.divide(new BigDecimal("1000"), radixLength, RoundingMode.HALF_UP);
            if (radixType.equalsIgnoreCase("非零进一")) {
                if (millisecondText.length() >= 2) {
                    String millisecondText2 = millisecondText.substring(1, 2);
                    if (millisecondText2.equals("0")) {
                        return divide;
                    } else {
                        return millisecondDecimal.divide(new BigDecimal("1000"), radixLength, RoundingMode.UP);
                    }
                }
            } else if (radixType.equalsIgnoreCase("四舍五入")) {
                return divide;
            }
        }
        return millisecondDecimal.divide(new BigDecimal("1000"), 3, RoundingMode.DOWN);
    }
}
